import json
import sys



import jieba

from py2neo import Graph
import re

class Neo4jNerService:
    def __init__(self):

        self.graph = Graph("http://localhost:7474", auth=("neo4j", "111111"))

    def find_similar_locations(self, text):

        text = text.replace('。', '，')
        # 使用正则表达式提取所需信息
        name_pattern = r"我叫(.*?)，"
        ethnicity_pattern = r"民族是(.*?)，"
        political_status_pattern = r"政治面貌是(.*?)，"
        college_pattern = r"专科院校是(.*?)，"
        specialty_pattern = r"专科专业是(.*?)，"
        registration_number_pattern = r"报名号是(.*?)，"
        examinee_number_pattern = r"考生号是(.*?)，"
        address_pattern = r"通知书邮寄地址是(.*?)，"
        recipient_pattern = r"通知书收件人是(.*?)，"
        postal_code_pattern = r"邮编是(.*?)，"
        foreign_language_pattern = r"外语语种是(.*?)，"
        exam_city_pattern = r"考点盟市(.*?)，"
        exam_specialty_pattern = r"报考专业是(.*?)，"
        wish_college_pattern = r"志愿院校是(.*?)，"
        wish_specialty_pattern = r"志愿专业是(.*?)，"

        # 搜索匹配的实体
        name = re.search(name_pattern, text).group(1) if re.search(name_pattern, text) else "xx"
        ethnicity = re.search(ethnicity_pattern, text).group(1) if re.search(ethnicity_pattern, text) else "汉族"
        political_status = re.search(political_status_pattern, text).group(1) if re.search(ethnicity_pattern, text) else "其他"
        college = re.search(college_pattern, text).group(1) if re.search(college_pattern, text) else "xx大学"
        specialty = re.search(specialty_pattern, text).group(1) if re.search(specialty_pattern, text) else "xx专业"
        registration_number = re.search(registration_number_pattern, text).group(1) if re.search(registration_number_pattern, text) else "xx"
        examinee_number = re.search(examinee_number_pattern, text).group(1) if re.search(examinee_number_pattern, text) else "xx"
        address = re.search(address_pattern, text).group(1) if re.search(address_pattern, text) else "xx省xx市xx区xx街道xx号"
        recipient = re.search(recipient_pattern, text).group(1) if re.search(recipient_pattern, text) else "xx"
        postal_code = re.search(postal_code_pattern, text).group(1) if re.search(postal_code_pattern, text) else "xx"
        foreign_language = re.search(foreign_language_pattern, text).group(1) if re.search(foreign_language_pattern, text) else "xx语"
        exam_city = re.search(exam_city_pattern, text).group(1) if re.search(exam_city_pattern, text) else "xx市"
        exam_specialty = re.search(exam_specialty_pattern, text).group(1) if re.search(exam_specialty_pattern, text) else "xx专业"
        wish_college = re.search(wish_college_pattern, text).group(1) if re.search(wish_college_pattern, text) else "xx大学"
        wish_specialty = re.search(wish_specialty_pattern, text).group(1) if re.search(wish_specialty_pattern, text) else "xx专业"



        # 精确模式，试图将句子最精确地切开，适合文本分析
        seg_list = jieba.cut(address, cut_all=False)
        result = "/".join(seg_list)
        lst = result.split("/")

        if '街' in lst[4] and '街' not in lst[3]:
            # 合并[4]号索引项和[3]号索引项
            lst[3] = f'{lst[3]}{lst[4]}'
            # 合并其后的所有索引项成一项
            lst[4:] = [''.join(lst[5:])]
        #print(add_results)
        locations = []
        address_list = []
        for entity in lst:  # results[0] 是一个包含实体信息的列表
            locations.append(entity)  # entity[0] 是实体的文本




        # countnum = len(locations)
        query0 = f"""
                    MATCH (n:Province)
                    WHERE n.name IS NOT NULL
                    WITH '{locations[0]}' AS inputText, n
                    ORDER BY apoc.text.levenshteinDistance(inputText, n.name) ASC
                    LIMIT 1
                    RETURN n.name, apoc.text.levenshteinDistance(inputText, n.name) AS distance
                    """
        result0 = self.graph.run(query0).data()
        province_name = result0[0].get("n.name") if result0 else "xx省"
        query1 = f"""
            MATCH (p:Province)-[:CONTAINS]->(c:City)
            WHERE p.name = '{province_name}'
            WITH '{locations[1]}' AS inputText, c
            ORDER BY apoc.text.levenshteinDistance(inputText, c.name) ASC
            LIMIT 1
            RETURN c.name, apoc.text.levenshteinDistance(inputText, c.name) AS distance
            """
        result1 = self.graph.run(query1).data()
        city_name = result1[0].get("c.name") if result1 else "xx市"
        query2 = f"""
            MATCH (c:City)-[:CONTAINS]->(d:County)
            WHERE c.name = '{city_name}'
            WITH '{locations[2]}' AS inputText, d
            ORDER BY apoc.text.levenshteinDistance(inputText, d.name) ASC
            LIMIT 1
            RETURN d.name, apoc.text.levenshteinDistance(inputText, d.name) AS distance
            """
        result2 = self.graph.run(query2).data()
        county_name = result2[0].get("d.name") if result2 else "xx区县"
        query3 = f"""
            MATCH (d:County)-[:CONTAINS]->(e:Block)
            WHERE d.name = '{county_name}'
            WITH '{locations[3]}' AS inputText, e
            ORDER BY apoc.text.levenshteinDistance(inputText, e.name) ASC
            LIMIT 1
            RETURN e.name, apoc.text.levenshteinDistance(inputText, e.name) AS distance
            """
        result3 = self.graph.run(query3).data()
        block_name = result3[0].get("e.name") if result3 else "xx街道"
        query4 = f"""
            MATCH (e:Block)-[:CONTAINS]->(f:Town)
            WHERE e.name = '{block_name}'
            WITH '{locations[4]}' AS inputText, f
            ORDER BY apoc.text.levenshteinDistance(inputText, f.name) ASC
            LIMIT 1
            RETURN f.name, apoc.text.levenshteinDistance(inputText, f.name) AS distance
            """
        result4 = self.graph.run(query4).data()
        town_name = result4[0].get("f.name") if result4 else "xx小区"

        # 初始化一个空字符串用于存储合并后的地名
        full_address = ""
        #合并地名
        if province_name:
            full_address += province_name
        if city_name:
            full_address += city_name
        if county_name:
            full_address += county_name
        if block_name:
            full_address += block_name
        if town_name:
            full_address += town_name
        # print("full_address:"+full_address)
        print("full_address:"+full_address)

        entitys = {
            "name": name,
            "ethnicity": ethnicity,
            "political_status": political_status,
            "college":college,
            "specialty": specialty,
            "registration_number": registration_number,
            "examinee_number": examinee_number,
            "address": full_address,
            "recipient": recipient,
            "postal_code": postal_code,
            "foreign_language": foreign_language,
            "exam_city": exam_city,
            "exam_specialty": exam_specialty,
            "wish_college": wish_college,
            "wish_specialty": wish_specialty
        }
        #     "专科院校": college,
        #     "专科专业": specialty,
        #     "报名号": registration_number,
        #     "考生号": examinee_number,
        #     "通知书邮寄地址": full_address,
        #     "通知书收件人": recipient,
        #     "邮编": postal_code,
        #     "外语语种": foreign_language,
        #     "考点盟市": exam_city,
        #     "报考专业": exam_specialty,
        #     "志愿院校": wish_college,
        #     "志愿专业": wish_specialty
        # }
        return json.dumps(entitys, ensure_ascii=False)



# 使用示例
if __name__ == "__main__":
    java_string = sys.argv[1]
    #print(f"Received from Java: {java_string}")
    service = Neo4jNerService()
    text = "我叫张小奔，我的民族是汉族，我的政治面貌是群众，我的专科院校是内蒙古师范大学专科。我的专科专业是云计算技术应用，我的报名号是026431。我的考生号是2415。我的通知书邮寄地址是内蒙古自治区呼和浩特市赛罕区大学东街翻斗花园，我的通知书收件人是张永贵，邮编是013350，我的外语语种是英语，我的考点模式是呼和浩特市，我的报考专业是计算机科学与技术。我的志愿院校是内蒙古工业大学，我的志愿专业是数据科学与大数据技术。"
    result = service.find_similar_locations(java_string)
    re = json.loads(result)
    print(re)
